import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
import eslintPlugin from 'vite-plugin-eslint';
import { visualizer } from 'rollup-plugin-visualizer';
import { UnifiedViteWeappTailwindcssPlugin as uvtw } from 'weapp-tailwindcss/vite';
import rem2px from 'postcss-rem-to-responsive-pixel';
import tailwindcss from 'tailwindcss';
import autoprefixer from 'autoprefixer';

const isH5 = process.env.UNI_PLATFORM === 'h5';
const isApp = process.env.UNI_PLATFORM === 'app';
const WeappTailwindcssDisabled = isH5 || isApp;

const postcssPlugins = [tailwindcss(), autoprefixer()];
const lifecycle = process.env.npm_lifecycle_event || '';

console.log('env', process.env.NODE_ENV);

if (!WeappTailwindcssDisabled) {
  postcssPlugins.push(
    rem2px({
      rootValue: 32,
      propList: ['*'],
      transformUnit: 'rpx',
    })
  );
}

// @ts-ignore
export default defineConfig(() => {
  return {
    build: {
      sourcemap: process.env.NODE_ENV === 'development',
    },
    plugins: [
      uni(),
      uvtw({
        disabled: WeappTailwindcssDisabled,
      }),
      eslintPlugin({
        include: ['*.js', '*.ts', 'src/**/*.ts', 'src/**/*.vue', 'src/*.ts', 'src/*.vue'],
      }),
      /report/.test(lifecycle) ? visualizer({ open: true, brotliSize: true, filename: 'report.html' }) : null,
    ],
    css: {
      postcss: {
        plugins: postcssPlugins,
      },
    },
  };
});
